#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    int pid;
    int rtn; /*子进程的返回数值*/
    int exec_errorno;
    char command[256];
    char *p;

    while (1)
    {
        /* 从终端读取要执行的命令 */
        printf(">");
        command[0] = '\0';
        p = fgets(command, 256, stdin);
        if (p == NULL)
        {
            perror("Error in fgets()");
            exit(-1);
        }

        // Delete the last char (new line) in the string returned by fgets()
        command[strlen(command) - 1] = '\0';

        // Quit if user inputs "quit"
        if (!strcmp(command, "quit"))
        {
            break;
        }

        // Create a child process to execute command
        pid = fork();
        if (pid < 0)
        {
            perror("Failed while calling fork");
            exit(-1);
        }
        else if (pid == 0)
        {
            /* 子进程执行此命令 */
            exec_errorno = execlp(command, command, NULL);
            /* 如果exec函数返回，表明没有正常执行命令 */
            /* 只有在这种情况下，才会执行下面的打印错误信息*/
            perror(command);
            exit(exec_errorno);
        }
        else
        {
            /* 父进程， 等待子进程结束，并打印子进程的返回值 */
            wait(&rtn);
            printf("\nValue returned from child process, rtn = %d\n", rtn);
            printf("WEXITSTATUS(rtn) = %d\n", WEXITSTATUS(rtn));
        }
    }

    return 0;
}
